<template>
    <div>
        <div class="row">
            <div class="col-md-5">
                <div class="row">

                    <span class="col-md-3 sm-hidden">选择年：</span>
                    <div class="col-md-6 col-sm-6">
                        <select v-model="year" class="form-control" v-on:change="calcYearSum(); calcMonthSum()">
                            <option v-for="yearInArray in YEAR_ARRAY">{{yearInArray}}</option>
                        </select>
                    </div>
                    <div class="col-md-3 col-sm-3">
                        <button type="button" class="btn btn-outline-info" v-on:click="addUp()">
                            <i class="fa fa-plus"></i>
                            新增
                        </button>
                    </div>
                </div>
                <br/>
                <div class="row">
                    <span class="col-md-3 sm-hidden">选择月：</span>
                    <div class="col-md-6 col-sm-6">
                        <select class="form-control" v-model="month" v-on:change="calcMonthSum()">
                            <option v-for="i in 12">{{i}}</option>

                        </select>
                    </div>
                    <div class="col-md-3 col-sm-3">
                        <button v-on:click="search()" type="button" class="btn btn-outline-primary">
                            <i class="fa fa-search"></i>
                            查看</button>
                    </div>

                </div>
            </div>

            <div class="col-md-3" v-show="year">
                <p class="align-bottom">{{year}}年总支出：{{year_sum}}</p>
                <p>{{year}}年平均日支出：{{year_avg}}</p>

            </div>

            <div class="col-md-3" v-show="month">
                <p>{{month}}月总支出：{{month_sum}}</p>
                <p>{{month}}月平均日支出：{{month_avg}}</p>

            </div>

        </div>
        <div class="col-md-12">
            <button id="refresh-button" v-on:click="onRefresh()" type="button" class="btn btn-outline-success">
                <i class="fa fa-refresh" v-show="!isRefresh"></i>
                <span v-show="isRefresh" class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
                刷新
            </button>
            <a href="javascript:void(0)" id="export-button" v-on:click="showExportDate()" style="float:right;">
                <i class="fa fa-download"></i>
                导出Excel
            </a>
        </div>

        <hr>

        <div class="row" >

            <div id="date-div" class="col-md-4">

                <table v-show="currentMonthDays.length!==0" id="level1-table"
                    v-bind:class="leftTableSmClass">
                    <thead class="thead-light">
                    <tr>
                        <th>{{searchYear}}年{{searchMonth}}月</th>
                    </tr>
                    </thead>
                    <tbody>
                    <tr v-for="day in currentMonthDays" v-on:click="onClickDate(day)"
                        v-bind:class="{'active': day === active}">
                        <td>{{day}}</td>
                    </tr>
                    </tbody>
                </table>
                <p v-show="currentMonthDays.length===0">当前月还没有记账信息！<a href="javascript:;" v-on:click="addUp()">点击添加</a></p>
            </div>

            <div id="cost-div" class="col-md-7">
                <div class="row">
                    <div class="col-md-6">
                        <button type="button" class="btn btn-outline-info" v-on:click="add()" title="增加一笔当天的支出">
                            <i class="fa fa-plus"></i>
                            新增当天
                        </button>
                    </div>

                    <div class="col-md-5">
                        <p>总计：<i class="fa fa-yen"></i>&nbsp;{{currentDaySum}}</p>
                    </div>
                </div>

                <table id="level2-table" v-bind:class="rightTableSmClass">
                    <thead class="thead-light">

                    <tr>
                        <th>日期</th>
                        <th>类型</th>
                        <th>金额</th>
                        <th>详情</th>
                        <th>操作</th>
                    </tr>
                    </thead>

                    <tbody>

                    <tr v-for="c in currentDayCosts">
                        <td>{{c.recordDate}}</td>
                        <td>{{COST_TYPE | optionKV(c.costType)}}</td>
                        <td>{{c.money}}</td>
                        <td>{{c.detail}}</td>

                        <td>
                            <div class="btn-group">

                                <button v-on:click="edit(c)" class="btn btn-sm btn-info">
                                    <i class="fa fa-pencil"></i>
                                </button>

                                <button v-on:click="del(c.id)" class="btn btn-sm btn-danger">
                                    <i class="fa fa-trash-o"></i>
                                </button>

                            </div>
                        </td>
                    </tr>

                    </tbody>
                </table>
                <div class="row graph-sm" id="cost-today">

                </div>
            </div>


        </div>

        <div id="export-modal" class="modal fade" tabindex="-1" role="dialog">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h4 class="modal-title">导出到Excel</h4>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>

                    </div>
                    <div class="modal-body">
                        <form class="form-horizontal">
                            <div class="form-group">
                                <label class="col-sm-10 custom-control-label">选择导出日期</label>
                                <div class="col-sm-10">
                                    <input type="text" id="export-range" class="form-control">
                                    <a style="float:right;" href="javascript:void(0)" @click="showViewModal()">预览</a>
                                </div>
                            </div>

                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary" v-on:click="exportExcel()">导出</button>
                    </div>
                </div><!-- /.modal-content -->
            </div><!-- /.modal-dialog -->
        </div>

        <div id="view-modal" class="modal fade" tabindex="-1" role="dialog">
            <div class="modal-dialog modal-lg" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h4 class="modal-title">{{ viewTitle }}</h4>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>

                    </div>
                    <div class="modal-body">
                        <table class="table table-hover table-sm table-striped text-center table-bordered">
                            <thead>
                            <tr>
                                <th>日期</th>
                                <th v-for="v in COST_TYPE">{{v.value}}</th>
                                <th>总计</th>
                            </tr>

                            </thead>
                            <tbody>

                            <tr v-for="cost in everydayCost">
                                <td>{{cost.recordDate}}</td>
                                <td v-for="v in COST_TYPE">{{cost.typeMoneyMap[v.value]}}</td>
                                <td>{{cost.sum}}</td>
                            </tr>
                            </tbody>
                        </table>
                    </div>
                </div><!-- /.modal-content -->
            </div><!-- /.modal-dialog -->
        </div>

        <div id="add-modal" class="modal fade" tabindex="-1" role="dialog">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h4 class="modal-title">账单</h4>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>

                    </div>
                    <div class="modal-body">
                        <form class="form-horizontal">
                            <div class="form-group">
                                <label class="col-sm-10 custom-control-label">日期</label>
                                <div class="col-sm-10">
<!--                                    <input v-show="!cost.id" class="form-control" v-model="active" disabled>-->
                                    <input class="form-control" v-model="cost.recordDate" disabled>
                                </div>
                            </div>

                            <div class="form-group">
                                <label class="col-sm-10 custom-control-label">支出类型</label>
                                <div class="col-sm-10">
                                    <select v-show="!cost.id" v-model="cost.costType" class="form-control">
                                        <option v-for="o in COST_TYPE" v-bind:value="o.key">
                                            {{o.value}}
                                        </option>
                                    </select>
                                    <select v-show="cost.id" v-model="cost.costType" class="form-control" disabled>
                                        <option v-for="o in COST_TYPE" v-bind:value="o.key">
                                            {{o.value}}
                                        </option>
                                    </select>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-10 custom-control-label">金额</label>
                                <div class="col-sm-10">
                                    <input type="number" v-model="cost.money" class="form-control" placeholder="输入金额" min="0">
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-10 custom-control-label">详情</label>
                                <div class="col-sm-10">
                                    <input v-model="cost.detail" class="form-control" placeholder="简要描述收入详情(10字以内)" maxlength="10">
                                </div>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary" v-on:click="save(2)">保存</button>
                    </div>
                </div><!-- /.modal-content -->
            </div><!-- /.modal-dialog -->
        </div><!-- /.modal -->

        <div id="add-modal-up" class="modal fade" tabindex="-1" role="dialog">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div v-show="ADD_TYPE === SINGLE">
                        <div class="modal-header">
                            <h4 class="modal-title">新增</h4>
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>

                        </div>
                        <div class="modal-body">
                            <form class="form-horizontal">
                                <div class="form-group">
                                    <label class="col-sm-10 custom-control-label">日期</label>
                                    <div class="col-sm-10">
                                        <input class="form-control" type="date" v-model="cost.recordDate">
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label class="col-sm-10 custom-control-label">支出类型</label>
                                    <div class="col-sm-10">
                                        <select v-model="cost.costType" class="form-control">
                                            <option v-for="o in COST_TYPE" v-bind:value="o.key">
                                                {{o.value}}
                                            </option>
                                        </select>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="col-sm-10 custom-control-label">金额</label>
                                    <div class="col-sm-10">
                                        <input type="number" v-model="cost.money" min="0" class="form-control" placeholder="输入金额"><i class="bi bi-calculator"></i>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="col-sm-10 custom-control-label">详情</label>
                                    <div class="col-sm-10">
                                        <input v-model="cost.detail" class="form-control" placeholder="简要描述收入详情(10字以内)" maxlength="10">
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>

                    <div v-show="ADD_TYPE === BATCH">
                        <div class="modal-header">
                            <h4 class="modal-title">批量新增</h4>
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>

                        </div>
                        <div class="modal-body">
                            <form class="form-horizontal">
                                <div class="form-group">
                                    <label class="col-sm-10 custom-control-label">选择日期范围</label>
                                    <div class="col-sm-10">
                                        <input id="daterange" class="form-control" type="text" value="">
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label class="col-sm-10 custom-control-label">支出类型</label>
                                    <div class="col-sm-10">
                                        <select v-model="costBatch.costType" class="form-control">
                                            <option v-for="o in COST_TYPE" v-bind:value="o.key">
                                                {{o.value}}
                                            </option>
                                        </select>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="col-sm-10 custom-control-label">金额</label>
                                    <div class="col-sm-10">
                                        <input type="number" v-model="costBatch.money" min="0" class="form-control" placeholder="输入金额"><i class="bi bi-calculator"></i>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="col-sm-10 custom-control-label">详情</label>
                                    <div class="col-sm-10">
                                        <input v-model="costBatch.detail" class="form-control" placeholder="简要描述收入详情(10字以内)" maxlength="10">
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <div style="width: 70%;">
                            <a href="javascript:;" @click="toAddBatch()" v-show="ADD_TYPE === SINGLE" style="float:left;">批量新增</a>
                            <a href="javascript:;" @click="toAddSingle()" v-show="ADD_TYPE === BATCH" style="float: left">单笔新增</a>
                        </div>
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                        <button type="button" v-show="ADD_TYPE === SINGLE" class="btn btn-primary" v-on:click="save(1)">保存</button>
                        <button type="button" v-show="ADD_TYPE === BATCH" class="btn btn-primary" v-on:click="saveBatch()">保存</button>
                    </div>
                </div><!-- /.modal-content -->
            </div><!-- /.modal-dialog -->
        </div><!-- /.modal -->

    </div>
</template>

<script>
    import Pagination from "../../components/Pagination";
    export default {
        name: 'Cost',
        components: {Pagination},
        data: function () {
            return {
                ADD_TYPE: "SINGLE",
                SINGLE: "SINGLE",
                BATCH: "BATCH",
                cost: {},
                costs: [],
                costBatch: {},
                currentMonthCosts: [],
                // 记录当月记账日期
                currentMonthDays: [],
                currentDayCosts: [],
                active: {},
                COST_TYPE: COST_TYPE,
                loginUser: null,

                year: null,
                month: null,
                day: null,

                searchYear: null,
                searchMonth: null,

                year_sum: 0,
                year_avg: 0,
                month_sum: 0,
                month_avg: 0,
                // 当日支出总和
                currentDaySum: 0,

                isRefresh: false,

                // 年份集合
                YEAR_ARRAY: YEAR_ARRAY,

                // 图表
                chart: null,

                startDate: '',
                endDate: '',
                exportStartDate: '',
                exportEndDate: '',

                // 预览标题
                viewTitle: '',
                // 预览展示的数据
                everydayCost: [],

                // themes: ['roma', 'macarons', 'shine', 'infographic', 'vintage', 'light', 'dark', 'default'],
                // theme: 'dark'
            }
        },
        computed:{
            leftTableSmClass(){
                return{
                    'table table-bordered table-hover table-sm': this.currentMonthDays.length >= 8,
                    'table table-bordered table-hover': this.currentMonthDays.length < 8,
                }
            },
            rightTableSmClass(){
                return{
                    'table table-bordered table-hover table-sm': this.currentDayCosts.length >= 4,
                    'table table-bordered table-hover': this.currentDayCosts.length < 4,
                }
            }
        },
        mounted: function () {
            let _this = this;
            let now = new Date();
            _this.year = now.getFullYear();
            _this.month = now.getMonth() + 1;
            _this.calcYearSum();
            _this.calcMonthSum();

            _this.loginUser = Tool.getLoginUser();
            _this.search();
            $("#cost-div").hide();

            // _this.theme = _this.themes[Math.floor(Math.random() * _this.themes.length)];

            // 初始化导出excel时间区间
            _this.exportStartDate = Tool.dateFormat('yyyy-MM-dd', now);
            _this.exportEndDate = Tool.dateFormat('yyyy-MM-dd', now);

            // 初始化批量增加的时间区间
            _this.startDate = Tool.dateFormat('yyyy-MM-dd', now);
            _this.endDate = Tool.dateFormat('yyyy-MM-dd', now);

            let lastYear = new Date();
            lastYear.setFullYear(now.getFullYear() - 1);
            let nextYear = new Date();
            nextYear.setFullYear(now.getFullYear() + 1);
            $('#daterange').daterangepicker({
                opens:'left',
                maxDate: Tool.dateFormat('MM/dd/yyyy', nextYear),
                minDate: Tool.dateFormat('MM/dd/yyyy', lastYear),
                showDropdowns: true,
                startDate: Tool.dateFormat('MM/dd/yyyy', now),
                endDate: Tool.dateFormat('MM/dd/yyyy', now)
            }, function(start, end, label) {
                console.log("选择了一个新的日期: "+start.format('YYYY-MM-DD') +' to '+end.format('YYYY-MM-DD'));
                _this.startDate = start.format('YYYY-MM-DD');
                _this.endDate = end.format('YYYY-MM-DD');
            });

            $('#add-modal-up input').on('keypress',function(event){
                if(event.keyCode === 13) {
                    if (_this.ADD_TYPE === _this.SINGLE) {
                        _this.save(1);
                    } else {
                        _this.saveBatch();
                    }
                }
            });
            $('#add-modal input').on('keypress',function(event){
                if(event.keyCode === 13) {
                    _this.save(2);
                }
            });
        },
        methods: {
            showViewModal() {
                let _this = this;
                $("#view-modal").modal("show");
                _this.viewTitle = _this.exportStartDate + '~' + _this.exportEndDate + ' 支出详情'
                _this.$ajax.get(process.env.VUE_APP_SERVER+'/business/cost/view?start=' + _this.exportStartDate + "&end=" + _this.exportEndDate).then(response=>{
                    let resp = response.data;
                    if (resp.success) {
                        _this.everydayCost = resp.content;
                    }
                })
            },
            /**
             * 点击导出excel
             */
            showExportDate() {
                let _this = this;
                $('#export-range').daterangepicker({
                    opens:'left',
                    showDropdowns: true,
                }, function(start, end, label) {
                    console.log("选择了一个新的日期: "+start.format('YYYY-MM-DD') +' to '+end.format('YYYY-MM-DD'));
                    _this.exportStartDate = start.format('YYYY-MM-DD');
                    _this.exportEndDate = end.format('YYYY-MM-DD');
                });
                $("#export-modal").modal("show");
            },
            /**
             * 导出excel
             */
            exportExcel() {
                let _this = this;
                _this.$ajax({
                    url: process.env.VUE_APP_SERVER+'/file/file/excel/download/cost?start=' + _this.exportStartDate + "&end=" + _this.exportEndDate,
                    method: "get",
                    header: {
                        headers: {'Content-Type': 'application/x-download'}
                    },
                    responseType: 'blob'
                }).then(response=>{
                    if (response.status === 200) {
                        let fileName = '支出报告_' + _this.exportStartDate + '-' + _this.exportEndDate + '.xls';
                        let blob = new Blob([response.data], {type: 'application/vnd.ms-excel'})
                        let url = window.URL.createObjectURL(blob);
                        let aLink = document.createElement("a");
                        aLink.style.display = "none";
                        aLink.href = url;
                        aLink.setAttribute("download", fileName);
                        document.body.appendChild(aLink);
                        aLink.click();
                        document.body.removeChild(aLink); //下载完成移除元素
                        window.URL.revokeObjectURL(url); //释放掉blob对象
                        $("#export-modal").modal("hide");
                    }else if(response.status === 401){
                        Toast.warning("当前登录状态已失效，请重新登录");
                        _this.$event.$emit("openLoginModal");
                        $("#export-modal").modal("hide");
                    } else if(response.status === 204) {
                        Toast.warning("无支出记录");
                    }
                })
            },
            /**
             * 跳转到单笔新增
             */
            toAddSingle() {
                this.ADD_TYPE = this.SINGLE;
            },

            toAddBatch() {
                this.ADD_TYPE = this.BATCH;
            },

            /**
             * 点击下方新增
             */
            add() {
                let _this = this;
                _this.cost = {};
                _this.cost.recordDate = _this.active;
                $("#add-modal").modal("show");
            },
            /**
             * 点击顶部新增
             */
            addUp() {
                let _this = this;
                _this.cost = {};
                // todo 日期为空问题待解决
                _this.costBatch = {};
                _this.toAddSingle();
                $("#add-modal-up").modal("show");
            },
            /**
             * 点击【保存】
             */
            save(type) {
                let _this = this;
                _this.cost.userId = Tool.getLoginUser().id;
                // 保存校验
                if(1 != 1
                    || !Validator.require(_this.cost.recordDate, "日期")
                    || !Validator.require(_this.cost.costType, "支出类型")
                    || !Validator.require(_this.cost.money, "金额")
                ) {
                    return;
                }

                _this.$ajax.post(process.env.VUE_APP_SERVER+'/business/cost/save',_this.cost).then((response) => {
                    let resp = response.data;
                    if(resp.success) {

                        if(type === 1){
                            $("#add-modal-up").modal("hide");
                            _this.search();
                        }else{
                            $("#add-modal").modal("hide");
                            _this.refresh();
                        }
                        Toast.success("保存成功！");

                    }else{
                        Toast.warning(resp.message);
                    }
                })
            },

            /**
             * 批量增加
             */
            saveBatch() {
                let _this = this;
                _this.costBatch.userId = Tool.getLoginUser().id;
                _this.costBatch.recordStartDate = _this.startDate;
                _this.costBatch.recordEndDate = _this.endDate;
                if(1 != 1
                    || !Validator.require(_this.costBatch.recordStartDate, "开始日期")
                    || !Validator.require(_this.costBatch.recordEndDate, "结束日期")
                    || !Validator.require(_this.costBatch.costType, "支出类型")
                    || !Validator.require(_this.costBatch.money, "金额")
                ) {
                    return;
                }

                _this.$ajax.post(process.env.VUE_APP_SERVER+'/business/cost/save-batch',_this.costBatch).then((response) => {
                    let resp = response.data;
                    if(resp.success) {
                        $("#add-modal-up").modal("hide");
                        _this.search();
                        Toast.success("保存成功！");
                    }else{
                        Toast.warning(resp.message);
                    }
                })
            },
            edit(cost) {
                let _this = this;
                _this.cost = $.extend({},cost);
                $("#add-modal").modal("show");
            },
            /**
             * 点击【删除】
             * @param id
             */
            del(id) {
                let _this = this;
                Confirm.show("删除支出后不可恢复，确认删除？", function () {
                    _this.$ajax.delete(process.env.VUE_APP_SERVER+'/business/cost/delete/'+id).then((response) => {
                        let resp = response.data;
                        if(resp.success) {
                            if(_this.currentDayCosts.length===1){
                                $("#cost-div").hide();
                            }
                            _this.refresh();
                            Toast.success("删除成功")
                        }
                    })
                })
            },

            /**
             * 点击【查看】
             */
            search(){
                let _this = this;
                _this.active = {};
                _this.searchYear = _this.year;
                _this.searchMonth = _this.month;
                $("#cost-div").hide();

                _this.loadData();
                _this.loadCounts();
            },

            loadData(){
                let _this = this;
                _this.loginUser = Tool.getLoginUser();
                _this.$ajax.get(process.env.VUE_APP_SERVER+'/business/cost/get-month-cost/'+_this.year + "/" + _this.month + "/" + _this.loginUser.id).then(response=>{
                    let resp = response.data;
                    if(resp.success){
                        _this.currentMonthCosts = resp.content;
                        _this.selectDay();
                    }
                })
            },

            /**
             * 左侧日期去重
             */
            selectDay(){
                let _this = this;
                _this.currentMonthDays = [];
                let len = _this.currentMonthCosts.length;

                for (let i = 0; i < len; i++) {
                    if(_this.currentMonthDays.indexOf(_this.currentMonthCosts[i].recordDate) === -1){
                        _this.currentMonthDays.push(_this.currentMonthCosts[i].recordDate);
                    }
                }
            },

            /**
             * 点击左侧日期
             */
            onClickDate(day){
                let _this = this;
                _this.active = day;
                _this.selectCurrentDayCosts(day);
                $("#cost-div").show();
                if(!_this.chart){
                    _this.initPieChart();
                }
                _this.setTitleOption();
                _this.setDataOption();
            },

            /**
             * 为图表设置数据
             */
            setDataOption(){
                let _this = this;
                let map = new Map();
                for(let i = 0;i<_this.currentDayCosts.length;i++){
                    let cost = _this.currentDayCosts[i];
                    let costType = cost.costType;
                    if (map.has(costType)) {
                        map.set(costType,map.get(costType)+cost.money);
                    }else{
                        map.set(costType,cost.money);
                    }
                }
                _this.chart.setOption({
                    series: [{
                        data:[
                            {value:map.get(COST_TYPE.HOUSE.key), name: COST_TYPE.HOUSE.value},
                            {value:map.get(COST_TYPE.MEDICAL.key), name: COST_TYPE.MEDICAL.value},
                            {value:map.get(COST_TYPE.CLOTHES.key), name: COST_TYPE.CLOTHES.value},
                            {value:map.get(COST_TYPE.SNACKS.key), name: COST_TYPE.SNACKS.value},
                            {value:map.get(COST_TYPE.EAT.key), name: COST_TYPE.EAT.value},
                            {value:map.get(COST_TYPE.COMMUNICATION.key), name: COST_TYPE.COMMUNICATION.value},
                            {value:map.get(COST_TYPE.FRUITS.key), name: COST_TYPE.FRUITS.value},
                            {value:map.get(COST_TYPE.DAILY.key), name: COST_TYPE.DAILY.value},
                            {value:map.get(COST_TYPE.TRAFFIC.key), name: COST_TYPE.TRAFFIC.value},
                            {value:map.get(COST_TYPE.EDUCATION.key), name: COST_TYPE.EDUCATION.value},
                            {value:map.get(COST_TYPE.OTHERS.key), name: COST_TYPE.OTHERS.value},
                        ].sort(function (a, b) { return a.value - b.value; })
                    }]
                })
            },

            /**
             * 为图表设置标题
             */
            setTitleOption(){
                let _this = this;
                let title = _this.active;
                let option = {
                    title:{
                        text: title
                    }
                }
                _this.chart.setOption(option);
            },

            /**
             * 初始化图表
             */
            initPieChart(){
                let _this = this;
                _this.chart = _this.$echarts.init(document.getElementById('cost-today'), 'light');

                _this.chart.setOption({
                    tooltip: {
                        trigger: 'item',
                        formatter: '{a} <br/>{b}: {c} ({d}%)',
                    },
                    legend: {
                        orient: 'vertical',
                        top: 30,
                        left: 10,
                    },
                    toolbox: {
                        feature: {
                            saveAsImage: {}
                        }
                    },

                    series: [{
                        name: '支出构成',
                        data: [],
                        radius: ['40%', '70%'],
                        // radius: '55%',
                        type: 'pie',
                        itemStyle: {
                            borderRadius: 10,
                            borderColor: '#fff',
                            borderWidth: 2
                        },
                        label: {
                            show: false,
                            position: 'center'
                        },
                        emphasis: {
                            label: {
                                show: true,
                                fontSize: '30',
                                fontWeight: 'bold'
                            },
                            itemStyle: {
                                shadowBlur: 10,
                                shadowOffsetX: 0,
                                shadowColor: 'rgba(0, 0, 0, 0.5)'
                            }
                        },
                        labelLine: {
                            show: true
                        },
                    }]
                })
            },

            /**
             * 查找当天支出
             * @param day
             */
            selectCurrentDayCosts(day){
                let _this = this;
                _this.currentDayCosts = [];
                _this.currentDaySum = 0;
                for(let i=0;i<_this.currentMonthCosts.length;i++){
                    if(day === _this.currentMonthCosts[i].recordDate){
                        _this.currentDayCosts.push(_this.currentMonthCosts[i]);
                        _this.currentDaySum += _this.currentMonthCosts[i].money;
                    }
                }
            },

            /**
             * 点击【刷新】
             */
            onRefresh(){
                let _this = this;
                _this.isRefresh = true;
                $("#refresh-button").attr("disabled",true);
                setTimeout(function () {
                    _this.isRefresh = false;
                    $("#refresh-button").removeAttr("disabled");
                },1000)
                _this.refresh();
            },

            refresh(){
                let _this = this;
                _this.loadData();
                _this.loadCounts();
                setTimeout(function () {
                    $('tr.active').trigger("click");
                },1000)
            },

            /**
             * 加载统计数据
             */
            loadCounts(){
                let _this = this;
                if(_this.year){
                    _this.calcYearSum();
                    if(_this.month){
                        _this.calcMonthSum();
                    }
                }
            },

            /**
             * 计算年总支出
             */
            calcYearSum(){
                let _this = this;
                _this.loginUser = Tool.getLoginUser();
                _this.$ajax.get(process.env.VUE_APP_SERVER+'/business/cost/get-cost-sum/' + _this.year + '/' + _this.loginUser.id).then(response=>{
                    let resp = response.data;
                    if(resp.success){
                        _this.year_sum = resp.content;
                        _this.year_avg = parseFloat((_this.year_sum / Tool.daysOf(_this.year,null)).toString()).toFixed(2);
                    }
                })
            },

            calcMonthSum(){
                let _this = this;
                _this.loginUser = Tool.getLoginUser();
                if(_this.month){
                    _this.$ajax.get(process.env.VUE_APP_SERVER+'/business/cost/get-cost-sum/' + _this.year + '/' + _this.month + '/' + _this.loginUser.id).then(response=>{
                        let resp = response.data;
                        if(resp.success){
                            _this.month_sum = resp.content;
                            _this.month_avg = parseFloat((_this.month_sum / Tool.daysOf(_this.year,_this.month)).toString()).toFixed(2);
                        }
                    })
                }
            },
        }
    }
</script>

<style scoped>
    #simple-table{
        background-color: white;
    }

    .active td{
        background-color: #d6e9c6 !important;
    }

    #export-button {
        text-decoration: none;
    }
</style>